package finalgame.Graphics;

import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.Image;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.opengl.Texture;

/**
 * Keep track of all the sprites, maybe something else
 */
public class RenderEngine {
	private static Map<String, Renderable> renderObj;
	private static Map<String, Texture> sprites;
	private static Map<String, Animation> animations;
	private static boolean init = false;
	
	static { // Initialize automatically after first use
		init();
	}
	
	/**
	 * Initialize render engine
	 */
	public static void init() {
		if(init) return;
		System.out.println("Render Engine init");
		renderObj = new HashMap<String, Renderable>();
		sprites = new HashMap<String, Texture>();
		animations = new HashMap<String, Animation>();
		init = true;
	}

	/**
	 * Register an object that can be rendered
	 */
	public static void register(Renderable r) {
		renderObj.put(r.getRenderID(), r);
	}

	/**
	 * Forget given object
	 * @param rid Render ID of that object
	 */
	public static void forget(String rid) {
		renderObj.remove(rid);
	}

	/**
	 * Get a registered sprite
	 * @param name The name of that sprite
	 */
	public static Texture getSprite(String name) {
		return sprites.get(name);
	}

	/**
	 * Register a sprite
	 */
	public static void registerSprite(String name, Texture tex) {
		sprites.put(name, tex);
	}

	/**
	 * Register all the sprites in a sprite sheet
	 * @param baseName The base name of the sprite sheet
	 * @param names All of the names for the sub-textures
	 * (Top-to-Bottom, then Left-to right)
	 * @param tex The base texture
	 * @param tw The width of each sub-texture
	 * @param th The height of each sub-texture
	 */
	public static void registerSpriteSheet(String baseName, String[] names,
			Texture tex, int tw, int th) {
		int w = tex.getImageWidth() / tw, h = tex.getImageHeight() / th;
		SpriteSheet ss = new SpriteSheet(new Image(tex), tw, th);
		for (int x = 0; x < w; x++) {
			for (int y = 0; y < h; y++) {
				registerSprite(baseName + names[y * w + x], ss.getSprite(x, y)
						.getTexture());
			}
		}
	}

	/**
	 * Forget a sprite
	 * @param name The name of the sprite to be forgotten
	 */
	public static void forgetSprite(String name) {
		sprites.remove(name);
	}
	
	/**
	 * Register all the sprites in a sprite sheet
	 * @param baseName The base name of the sprite sheet
	 * @param length
	 * @param tex The base texture
	 */
	public static void registerAnimation(String baseName, int length, Image tex) {
		int tw = tex.getWidth() / length, h = tex.getHeight();
		SpriteSheet ss = new SpriteSheet(tex, tw, h);
		animations.put(baseName, new Animation(ss, 150));
	}
	
	/**
	 * Get a registered animation
	 * @param name The name of that animation
	 */
	public static Animation getAnimation(String name) {
		return animations.get(name);
	}
}
